<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Model\UserEnergy;
use App\Model\UserEnergyLog;
use App\Model\UserModel;
use App\Model\ConfigModel;
use Illuminate\Support\Facades\DB;
use AlibabaCloud\Client\AlibabaCloud;

use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use App\Model\UserAuthModel;
use App\User;


class VerifyController extends Controller
{
	//判断该身份证信息是否存在
	public function verify_exit(){
		$name = request()->name;
		$idcard = request()->idcard;

		if(empty($name)){
			return ['code'=>0,'msg'=>'请输入真实姓名'];
		}
		if(empty($idcard)){
			return ['code'=>0,'msg'=>'请输入身份证号'];
		}
		$list = UserAuthModel::where('name',$name)->where('idcard',$idcard)->first();
		if($list){
			return ['code'=>0,'msg'=>'该身份证信息已认证'];
		}else{
			return ['code'=>1,'msg'=>'正常认证'];
		}

	}
	//获取token
	public function verify_token(){
		// Download：https://github.com/aliyun/openapi-sdk-php
		// Usage：https://github.com/aliyun/openapi-sdk-php/blob/master/README.md
		$uid = request()->uid;
		$name = request()->name;
		$idcard = request()->idcard;
		if(empty($name)){
			return ['code'=>0,'msg'=>'请输入真实姓名'];
		}
		if(empty($idcard)){
			return ['code'=>0,'msg'=>'请输入身份证号'];
		}

		$auth_name = "/^[\x{4e00}-\x{9fa5}]{2,6}$/u";
		$str = "/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/";
		if (!preg_match($auth_name, request()->name)) {
			return ['code' => 0, 'msg' => retStrInfo(50)];
		}
		if (!preg_match($str, $idcard)) {
			return ['code' => 0, 'msg' => retStrInfo(51)];
		}
		$list = UserAuthModel::where('name',$name)->where('idcard',$idcard)->first();
		if($list){
			return ['code'=>0,'msg'=>'该身份证信息已认证'];
		}
		AlibabaCloud::accessKeyClient('LTAI4G1f6c6HyeqhmCRjokK6','sICS1DZ5MHxmy9UdGLocrxSTt19Ijh')
			->regionId('cn-hangzhou')
			->asDefaultClient();

		try {
			$result = AlibabaCloud::rpc()
				->product('Cloudauth')
				// ->scheme('https') // https | http
				->version('2019-03-07')
				->action('DescribeVerifyToken')
				->method('POST')
				->host('cloudauth.aliyuncs.com')
				->options([
					'query' => [
						'RegionId' => "cn-hangzhou",
						'BizType' => "RPBioOnly",
						'BizId' => $uid,
						'Name' => $name,
						'IdCardNumber' => $idcard,
					],
				])
				->request();
			$result = $result->toArray();
			return ['code'=>1,'msg'=>'返回数据','data'=>$result];
		} catch (ClientException $e) {
			echo $e->getErrorMessage() . PHP_EOL;
		} catch (ServerException $e) {
			echo $e->getErrorMessage() . PHP_EOL;
		}
	}

	//认证结果
	public function verify_result(){
		$uid = request()->uid;
		AlibabaCloud::accessKeyClient('LTAI4G1f6c6HyeqhmCRjokK6','sICS1DZ5MHxmy9UdGLocrxSTt19Ijh')
			->regionId('cn-hangzhou')
			->asDefaultClient();

		try {
			$result = AlibabaCloud::rpc()
				->product('Cloudauth')
				// ->scheme('https') // https | http
				->version('2019-03-07')
				->action('DescribeVerifyResult')
				->method('POST')
				->host('cloudauth.aliyuncs.com')
				->options([
					'query' => [
						'RegionId' => "cn-hangzhou",
						'BizId' => $uid,
						'BizType' => "RPBioOnly",
					],
				])
				->request();
			$result = $result->toArray();
			if($result['VerifyStatus'] == 1){
				$user_auth = UserAuthModel::where('uid',$uid)->first();
				DB::beginTransaction();
				try{
					if(empty($user_auth)){
						//记录用户的身份证信息
						$name = $result['Material']['IdCardName'];
						$idcard = $result['Material']['IdCardNumber'];
						// $idcardt = $result['Material']['IdCardInfo']['FrontImageUrl'];
						// $idcardf = $result['Material']['IdCardInfo']['BackImageUrl'];

						UserAuthModel::create([
							'uid' => $uid,
							'name' => $name,
							'idcard' => $idcard,
							// 'idcard_headz' => $idcardt,
							// 'idcard_headf' => $idcardf,
						]);
					}
					UserModel::where('id',$uid)->update(['is_auth'=>1]);
					//用户信息
					$user_list = UserModel::where('id',$uid)->first();
					//下级实名认证，给上级赠送红桶
					$auth_red_num = ConfigModel::getValue('auth_red_num');
					$auth_blue_num = ConfigModel::getValue('auth_blue_num');
					//查询上级
					if($user_list['pid'] > 0){
						//判断是否赠送
						$user_send_exit = UserEnergyLog::where('uid',$user_list['pid'])->where('tid',$uid)->where('type',3)->first();
						if(!$user_send_exit){
							//查询上级信息
						$puser = UserModel::where('id',$user_list['pid'])->first();
						//判断上级是否实名认证
						if($puser['is_auth'] == 1){
							//查询上级是否存在汽油
							$user_energy = UserEnergy::where('uid',$puser['id'])->first();
							//赠送1桶蓝汽油.1桶红汽油
							if($user_energy){
								$user_energy->increment('oth_num',$auth_red_num);
								$user_energy->increment('oth_num_two',$auth_blue_num);
							}else{
								UserEnergy::create([
									'uid' => $puser['id'],
									'oth_num' => $auth_red_num,
									'oth_num_two' => $auth_blue_num,
								]);
							}
							//添加赠送日志
							UserEnergyLog::add_log($puser['id'],1,'+','3','2','成功邀请好友['.$user_list['user'].']获得'.$auth_red_num.'桶红汽油',$user_list['id'],0,0,1,0,0);
							UserEnergyLog::add_log($puser['id'],1,'+','3','4','成功邀请好友['.$user_list['user'].']获得'.$auth_blue_num.'桶蓝汽油',$user_list['id'],0,0,0,0,1);
						}
						}
						
					}
					DB::commit();
				}catch(Exception $e){
					DB::rollBack();
					return ['code'=>1,'msg'=>'认证成功'];
				}
			}
			return ['code'=>1,'msg'=>'认证成功','data'=>$result];
		} catch (ClientException $e) {
			echo $e->getErrorMessage() . PHP_EOL;
		} catch (ServerException $e) {
			echo $e->getErrorMessage() . PHP_EOL;
		}
	}
}